﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;

using Skype4MP.Enums;

using MediaPortal.Configuration;
using MediaPortal.Dialogs;
using MediaPortal.GUI.Library;
using MediaPortal.Localisation;
using System.Runtime.InteropServices;
using System.Threading;

namespace Skype4MP.Utils
{
  public static class Skype4MPUtils
  {
/*
    #region Constants

    public static int MAIN_WINDOW_ID = 1911;
    public static int SKYPEOUT_WINDOW_ID = 1913;
    public static int HISTORY_WINDOW_ID = 1914;
    public static int ACCEPTANCE_WINDOW_ID = 1917;

    public const string PLUGIN_DESCRIPTION = "Skype plugin for Mediaportal";
    public const string PLUGIN_AUTHOR = "Fripsy";
    public const string PLUGIN_NAME = "Skype4MP";
    public static string FileName = "Skype4MP.xml";

    public const string SKIN_MEDIA_DIR = @"\Media\Skype4MP\";
    public const string IMG_STATUS_NOTAVAIL = "PresenceAway_48x48.png";
    public const string IMG_STATUS_OFFLINE = "PresenceOffline_48x48.png";
    public const string IMG_STATUS_ONLINE = "PresenceAvailable_48x48.png";
    public const string IMG_STATUS_DONOTDIST = "PresenceDoNotDisturb_48x48.png";
    public const string IMG_STATUS_AWAY = "PresenceAway_48x48.png";
    public const string IMG_STATUS_SKYPEOUT = "SkypeOutInactive_128x128.png";
    public const string IMG_STATUS_SKYPEME = "StatusSkypeMe_128x128.png";
    public const string IMG_INCOMING_CALL = "CallIn_128x128.png";
    public const string IMG_OUTGOING_CALL = "CallOut_128x128.png";
    public const string IMG_MISSED_CALL = "CallMissed_128x128.png";

    public const string IMG_SKYPE_ICON = "SkypeBlue_128x128.png";

    public const string EMPTY_STRING = " ";

    public const int SW_SHOWNORMAL = 1;
    public const int SW_SHOWMINIMIZED = 2;
    public const int SW_SHOWMAXIMIZED = 3;
    public const int WM_SYSKEYDOWN = 0x104;
    public const int WM_CLOSE = 0x0010;


    #endregion
    */
    /*
    public string STATUS_ONLINE = GetLocalizedLabel(0);
    public const string STATUS_OFFLINE = GetLocalizedLabel(1);
    public const string STATUS_NOTAVAILABLE = GetLocalizedLabel(2);
    public const string STATUS_INVISIBLE = GetLocalizedLabel(3);
    public const string STATUS_DONOTDISTURB = GetLocalizedLabel(4);
    public const string STATUS_AWAY = GetLocalizedLabel(5);
    public const string STATUS_SKYPEME = GetLocalizedLabel(6);
    public const string STATUS_SKYPEOUT = GetLocalizedLabel(7);
    public const string STATUS_UNKNOWN = GetLocalizedLabel(8);
    */


    private static LocalisationProvider _localizationStrings;

    private static bool _localizationLoaded;

    public static void LoadLocalization()
    {
      _localizationLoaded = false;
      //string localizationFile = Config.GetSubFolder(Config.Dir.Language, @"InfoService\strings_en.xml");
      //logger.WriteLog("Try to load localization " + localizationFile, LogLevel.Debug, InfoServiceModul.InfoService);
      string localizationDirectory = Config.GetSubFolder(Config.Dir.Language, "Skype4MP");
      if (Directory.Exists(localizationDirectory))
      {
        Log.Debug("Skype4MP ==> Looking for user language");
        string language = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")).GetValueAsString("skin", "language", "English");
        string localizationCultureName = string.Empty;
        if (!string.IsNullOrEmpty(language))
        {
          Log.Debug("Skype4MP ==> User language is " + language + ". Load localization...");
          localizationCultureName = GUILocalizeStrings.GetCultureName(language);
          if (File.Exists(Config.GetSubFolder(Config.Dir.Language, @"Skype4MP\strings_" + localizationCultureName + ".xml")))
          {
            _localizationStrings = new LocalisationProvider(localizationDirectory, localizationCultureName);
            GUILocalizeStrings.Load(language);
            _localizationLoaded = true;
          }
          else Log.Error("Skype4MP ==> Couldn't find user language " + Config.GetSubFolder(Config.Dir.Language, @"Skype4MP\strings_" + localizationCultureName + ".xml") + " for Skype4MP");
        }
        else Log.Error("Skype4MP ==> Couldn't get the user language. Didn't find user language from MediaPortal");
      }
      else Log.Error("Skype4MP ==> Localization file doesn't exist. Folder " + localizationDirectory + " doesn't exist");
    }

    public static string GetLocalizedLabel(int id)
    {
      return _localizationLoaded ? _localizationStrings.GetString("unmapped", id) : string.Empty;
    }

    public static void ShowDialogOkWindow(string header, string text)
    {
      //logger.WriteLog("Show dialog window", LogLevel.Info, InfoServiceModul.InfoService);
      GUIDialogOK window = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
      window.SetHeading(header);
      List<string> textCol = new List<string>();
      int lastIndex = 0;
      for (int i = 44; i < text.Length; i += 45)
      {
        if (text[i] != ' ' || text[i] != ',' || text[i] != '.')
        {
          while (i > 1)
          {
            i--;
            if (text[i] == ' ' || text[i] == ',' || text[i] == '.')
            {
              break;
            }
          }
        }
        textCol.Add(text.Substring(lastIndex, i - lastIndex));
        lastIndex = i;
      }
      textCol.Add(text.Substring(lastIndex, text.Length - lastIndex));
      for (int i = 0; i < textCol.Count; i++) textCol[i] = textCol[i].Trim();
      for (int i = 1; i <= 4; i++)
      {
        if (i <= textCol.Count) window.SetLine(i, textCol[i - 1]);
      }
      //window.FlowDirection = FlowDirection.RightToLeft;
      window.DoModal(GUIWindowManager.ActiveWindow);

    }

    public static string GetTimeDifferenceToNow(DateTime datetime)
    {
      //logger.WriteLog("Calc time difference", LogLevel.Debug, InfoServiceModul.InfoService);
      if (datetime.Date != new DateTime())
      {
        TimeSpan diff = (DateTime.Now - datetime);
        if (diff.TotalSeconds >= 1)
        {
          if (diff.TotalSeconds >= 1 && diff.TotalSeconds < 60)
          {
            return string.Format(GetLocalizedLabel(20), (int)diff.TotalSeconds);
          }
          if (diff.TotalMinutes < 60 && diff.TotalMinutes >= 1)
          {
            return string.Format(GetLocalizedLabel(21), (int)diff.TotalMinutes);
          }
          if (diff.TotalHours < 24 && diff.TotalHours >= 1)
          {
            return string.Format(GetLocalizedLabel(22), (int)diff.TotalHours, diff.Minutes);
          }
          if (diff.TotalDays >= 1)
          {
            return string.Format(GetLocalizedLabel(23), (int)diff.TotalDays, diff.Hours, diff.Minutes);
          }
        }
      }
      //logger.WriteLog("Cannot calc time difference. Feed item has no Date/Time", LogLevel.Warning, InfoServiceModul.InfoService);
      return "";
    }

    public static bool ShowKeyboard(int window, ref string sString)
    {
      //logger.WriteLog("Show keyboard", LogLevel.Info, InfoServiceModul.InfoService);
      VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
      if (null == keyboard)
      {
        return false;
      }
      keyboard.IsSearchKeyboard = false;
      keyboard.Reset();
      keyboard.Text = sString;
      keyboard.DoModal(window);
      if (keyboard.IsConfirmed)
      {
        sString = keyboard.Text;
      }
      return keyboard.IsConfirmed;
    }

    public static bool IsValidPath(string path)
    {
      if (!string.IsNullOrEmpty(path))
      {
        Regex r = new Regex(@"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$");
        return r.IsMatch(path);
      }
      return false;
    }

	public static void MoveMouseCursorToWindowPositionAndClick(int windowHandle, int x, int y)
	{
		Skype4MP.SkypeHelper.SkypeWin32.INPUT aInput = new Skype4MP.SkypeHelper.SkypeWin32.INPUT();

		Skype4MP.SkypeHelper.SkypeWin32.POINT windowPoint = new Skype4MP.SkypeHelper.SkypeWin32.POINT();
		windowPoint.x = x;
		windowPoint.y = y;
		Skype4MP.SkypeHelper.SkypeWin32.ClientToScreen(new IntPtr(windowHandle), ref windowPoint);

		// mouse_event ABSOLUTE coords run from 0 to 65535  
		int x_abs = (int)(65535f / System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width * windowPoint.x);
		int y_abs = (int)(65535f / System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height * windowPoint.y);

		aInput.type = Skype4MP.SkypeHelper.SkypeWin32.INPUT_MOUSE;
		aInput.mi.dwFlags = Skype4MP.SkypeHelper.SkypeWin32.MOUSEEVENTF_MOVE | Skype4MP.SkypeHelper.SkypeWin32.MOUSEEVENTF_ABSOLUTE;
		aInput.mi.dx = x_abs;
		aInput.mi.dy = y_abs;
		aInput.mi.dwExtraInfo = 0;
		aInput.mi.mouseData = 0;
		aInput.mi.time = 0;

		int resSendInput = Skype4MP.SkypeHelper.SkypeWin32.SendInput(1, ref aInput, Marshal.SizeOf(aInput));
		if (resSendInput == 0) System.Diagnostics.Debug.WriteLine(Marshal.GetLastWin32Error());

		Thread.Sleep(100);

		aInput.mi.dy += 10;
		resSendInput = Skype4MP.SkypeHelper.SkypeWin32.SendInput(1, ref aInput, Marshal.SizeOf(aInput));
		if (resSendInput == 0) System.Diagnostics.Debug.WriteLine(Marshal.GetLastWin32Error());

		Thread.Sleep(500);

		aInput.mi.dy -= 10;
		resSendInput = Skype4MP.SkypeHelper.SkypeWin32.SendInput(1, ref aInput, Marshal.SizeOf(aInput));
		if (resSendInput == 0) System.Diagnostics.Debug.WriteLine(Marshal.GetLastWin32Error());

		Thread.Sleep(500);

		aInput = new Skype4MP.SkypeHelper.SkypeWin32.INPUT();
		aInput.type = Skype4MP.SkypeHelper.SkypeWin32.INPUT_MOUSE;
		aInput.mi.dwFlags = Skype4MP.SkypeHelper.SkypeWin32.MOUSEEVENTF_LEFTDOWN;

		resSendInput = Skype4MP.SkypeHelper.SkypeWin32.SendInput(1, ref aInput, Marshal.SizeOf(aInput));
		if (resSendInput == 0) System.Diagnostics.Debug.WriteLine(Marshal.GetLastWin32Error());

		Thread.Sleep(50);

		aInput = new Skype4MP.SkypeHelper.SkypeWin32.INPUT();
		aInput.mi.dwFlags = Skype4MP.SkypeHelper.SkypeWin32.MOUSEEVENTF_LEFTUP;

		resSendInput = Skype4MP.SkypeHelper.SkypeWin32.SendInput(1, ref aInput, Marshal.SizeOf(aInput));
		if (resSendInput == 0) System.Diagnostics.Debug.WriteLine(Marshal.GetLastWin32Error());
	}
  }
}
